<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 小程序公共API服务
 */
namespace app\bestbao\controller\api\v1;
use app\common\facade\Inform;
use app\bestbao\controller\api\Base;
use app\bestbao\model\BestbaoEngineer;
use app\bestbao\model\BestbaoOrder;
use app\bestbao\model\BestbaoProduct;
use app\bestbao\model\BestbaoProcess;
use app\common\model\SystemUserAddress;
use app\common\event\User as CommonUser;
use app\common\facade\WechatPay;
use app\common\facade\Upload;
use filter\Filter;

class Order extends Base{


    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }
 
    /**
     * 我的订单
     * @return void
     */
    public function index(){
        $param = [
            'page'  => $this->request->param('page/d',0),
            'types' => $this->request->param('types/d',0),
            'sign'  => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['uid']               = $this->user->id;
        $condition['state']             = $param['types'];
        $order = BestbaoOrder::where($condition)->field('id,title,update_time,urgent,state,engineer_id,phone,realname,address,engineer_id')->order('id desc')->page($param['page'],10)->select();
        if($order->isEmpty()){
            return enjson(0);
        }
        $data = $order->toArray();
        foreach ($data as $key => $value) {
            $data[$key]['update_time'] = date('Y-m-d H:i',$value['update_time']);
            $data[$key]['state_text']  = BestbaoOrder::stateText($value['state'],$value['engineer_id']);
        }
        return enjson(200,'操作成功',$data);
    }

    /**
     * 订单详情
     * @return void
     */
    public function reView(){
        $param = [
            'id'   => $this->request->param('id'),
            'sign' => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['uid']               = $this->user->id;
        $condition['id']                = $param['id'];
        $order = BestbaoOrder::where($condition)->find();
        if(empty($order)){
            return enjson(0);
        }
        $order['update_time'] = date('Y-m-d H:i',$order['update_time']);
        $order['state_text']  = BestbaoOrder::stateText($order['state'],$order['engineer_id']);
        $order['imgs']        = json_decode($order['imgs'],true);
        $order['solve_time'] = empty($order['solve_time'])?'':date('Y-m-d H:i',$order['solve_time']);
        $info = BestbaoProcess::where(['order_id' => $param['id']])->select();
        $process = [];
        foreach ($info as $key => $value) {
            $process[$key]['text'] = $value['remarks'];
            $process[$key]['desc'] = date('Y-m-d H:i',$value['create_time']);
        }
        return enjson(200,'操作成功',['order'=>$order,'process' =>$process]);
    }

    /**
     * 提交维修订单
     * @return void
     */
    public function add(){
        if(request()->isPost()){
            $param = [
                'order_product_id' => $this->request->param('order_product_id/d',0),
                'urgent'           => $this->request->param('urgent/d',0),
                'title'            => $this->request->param('title/s'),
                'question'         => $this->request->param('question/s',''),
                'imgs'             => $this->request->param('imgs/s','[]','htmlspecialchars_decode'),
                'video'            => $this->request->param('video/s','[]','htmlspecialchars_decode'),
                'sound'            => $this->request->param('sound/s','[]','htmlspecialchars_decode'),
                'address'          => $this->request->param('address/d',0),
                'sign'             => $this->request->param('sign/s'),
            ];
            $rel = $this->apiSign($param);
            if($rel['code'] != 200){
                return enjson($rel['code'],'签名验证失败');
            }
            $validate = $this->validate($param,'Order.order');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            //判断是否允许提交
            $is_order =  BestbaoOrder::where(['uid'=>$this->user->id,'state' => 1])->find();
            if($is_order){
                return enjson(301,'你还有欠费工单,请先把欠费工单结清.',['url'=>'/pages/order/review?id='.$is_order->id]);
            }
            //读取发货地址
            $address = SystemUserAddress::where(['user_id'=>$this->user->id,'id' =>$param['address']])->find();
            if(empty($address)){
                return enjson(403,'请选择收货地址');
            }
            $sound = Filter::filter_escape(json_decode($param['sound'],true));
            $video = Filter::filter_escape(json_decode($param['video'],true));
            //查询产品
            $product = BestbaoProduct::where(['id' =>$param['order_product_id']])->field('id')->find();
            $order['member_miniapp_id'] = $this->miniapp_id;
            $order['title']             = $param['title'];
            $order['question']          = $param['question'];
            $order['urgent']            = $param['urgent'];
            $order['uid']               = $this->user->id;
            $order['product_id']        = empty($product) ? 0 : $product->id;
            $order['imgs']              = json_encode(Filter::filter_escape(json_decode($param['imgs'],true)));
            $order['sound']             = empty($sound) ? '': $sound[0];
            $order['video']             = empty($video) ? '': $video[0];
            $order['realname']          = $address['name'];
            $order['phone']             = $address['telphone'];
            $order['address']           = $address['address'];
            $result =  BestbaoOrder::create($order);
            if($result){
                BestbaoProcess::create(['member_miniapp_id' => $this->miniapp_id,'order_id' => $result->id,'engineer_id'  => 0,'remarks' => '创建工单']);
                //通知到工程师
                $list = BestbaoEngineer::where(['member_miniapp_id' => $this->miniapp_id])->select()->toArray();
                foreach ($list as $info){
                    Inform::sms($info['uid'],$this->miniapp_id,['title' =>'业务进展通知','type' => '新工单申请','content' =>'您有新的工单待接受','state' => '待收单']);
                }
                return enjson(200,'操作成功',['url'=>url('ask/index')]);
            }else{
                return enjson(0);
            }
        }
    }

    /**
     * 商城图片
     * @return void
     */
    public function upImg(){
        if(request()->isPost()){
            $rel = Upload::index();
            if($rel['error'] == 0){
                return json(['code'=>200,'msg'=>'success','data' => $rel['url']]);
            }else{
                return json(['code'=>204,'msg'=>'error']);
            }
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * 解决方案订阅
     * */
    public function doBuy(){
        $param['sign']    = $this->request->param('sign');
        $param['id']      = $this->request->param('id');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['uid']               = $this->user->id;
        $condition['id']                = $param['id'];
        $condition['state']             = 1;
        $order = BestbaoOrder::where($condition)->find();
        if(empty($order)){
            return enjson(403,'未找到需要付费的工单');
        }
        //唤醒微信支付参数
        $order->order_no = $this->user->invite_code.order_no(); //订单号
        $order->save();
        $payparm = [
            'openid'     => $this->user->miniapp_uid,
            'miniapp_id' => $this->miniapp_id,
            'name'       => '支付工单费用',
            'order_no'   => $order->order_no,
            'total_fee'  => $order->price*100,
            'notify_url' => api(1,'bestbao/notify/order',$this->miniapp_id),
        ];
        $ispay = WechatPay::orderPay($payparm);
        if ($ispay['code'] == 0) {
            return enjson(403,$ispay['msg']);
        }else{
            //通知到后台管理者微信
            Inform::sms(CommonUser::isFounder($this->miniapp_id)->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '订单付款','content' =>'您有新的订单付款信息','state' => '已完成']);
            return enjson(200,'成功',$ispay['data']);
        }
    }

    //星级评价
    public function rate(){
        if(request()->isPost()){
            $param['sign'] = $this->request->param('sign');
            $param['id']   = $this->request->param('id');
            $param['rate'] = $this->request->param('rate/d',1);
            $rel = $this->apiSign($param);
            if($rel['code'] != 200){
                return enjson($rel['code'],'签名验证失败');
            }
            $condition['member_miniapp_id'] = $this->miniapp_id;
            $condition['uid']               = $this->user->id;
            $condition['id']                = $param['id'];
            $condition['state']             = 2;
            $order = BestbaoOrder::where($condition)->find();
            if(empty($order)){
                return enjson(403,'未找到需要评价的工单');
            }
            $order->rate  = $param['rate']; //评级值
            $order->state = 3; //关闭订单
            $order->save();
            //进程
            BestbaoProcess::create(['member_miniapp_id' => $this->miniapp_id,'order_id' => $order->id,'engineer_id'  => 0,'remarks' => '工单关闭']);
            //通知到工程师
            $engineer = BestbaoEngineer::where(['id' => $order->engineer_id])->find();
            if(!empty($engineer)){
                Inform::sms($engineer->uid,$this->miniapp_id,['title' =>'业务进展通知','type' => '订单评价','content' =>'您的订单有新的评价信息','state' => '已完成']);
            }
            return enjson(200,'成功');
        }
    }

    //读取订单数量
    public function statis(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //查询用户的工程师
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id,level,title')->count();
        $condition['member_miniapp_id'] = $this->miniapp_id;
        if($engineer){
            $condition['engineer_id'] = $this->user->id;
        }else{
            $condition['uid'] = $this->user->id;
        }
        $data = [];
        $data['all']      = BestbaoOrder::where($condition)->count();
        $data['progress'] = BestbaoOrder::where($condition)->where(['state' => 0])->count();
        $data['arrears']  = BestbaoOrder::where($condition)->where(['state' => 1])->count();
        return enjson(200,'成功',$data);
    }
}